package com.shaoshaohuo.app.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.AllOrderListViewAdapter;
import com.shaoshaohuo.app.adapter.MyBaseAdapter;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.OperateEntity;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.framework.ActivityCollector;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.net.HttpConfig;
import com.shaoshaohuo.app.net.NewHttpCofig;
import com.shaoshaohuo.app.net.RequestParam;
import com.shaoshaohuo.app.net.ShopHttpConfig;
import com.shaoshaohuo.app.utils.Okhttputils;
import com.shaoshaohuo.app.utils.ToastUtil;
import com.shaoshaohuo.app.utils.im.IMFactory;
import com.umeng.analytics.MobclickAgent;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 运营
 * Created by Administrator on 2017/6/22.
 */

public class OperateActivity extends BaseActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    private ImageView order_tobar_back;
    private TextView order_tobar_enter;
    private ImageView order_tobar_right;
    private LinearLayout order_layout_topbar_left;

    private ListView listView;
    private Button btn_fh;
    private Myadapter myadapter;
    private SwipeRefreshLayout swp;
    private TextView tv_back;
    private TextView textView_tobar_left;


    private EditText shop_search_edit;
    private TextView shop_search_tv;
    private boolean flag = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_operalayout);
        init();
        network();
    }

    private void network() {
        Map<String, String> headerParams = RequestParam.getHeaderParams();
        Okhttputils.Instanse(this).getnet(headerParams, this, HttpConfig.BASE_HOST_URL + NewHttpCofig.pushlist, new Okhttputils.OkutListener() {
            @Override
            public void error(Call call, IOException e) {

            }

            @Override
            public void error(Call call, int code) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (myadapter != null) {
                            myadapter.setData(new ArrayList<OperateEntity.DataBeanX.DateBean>());
                        }
                    }
                });

            }

            @Override
            public void suseff(Call call, Response response, Object o) {
                OperateEntity operateEntity = (OperateEntity) o;
                final OperateEntity.DataBeanX.AreaDateBean areaDate = operateEntity.getData().getAreaDate();
                final List<OperateEntity.DataBeanX.DateBean> date = operateEntity.getData().getDate();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        order_tobar_enter.setText(areaDate.getPhone());
                        textView_tobar_left.setText(areaDate.getArea());
                        myadapter = new Myadapter(getApplicationContext(), date, false);
                        listView.setAdapter(myadapter);
                    }
                });
            }
        }, OperateEntity.class);
    }

    private void init() {
        textView_tobar_left = (TextView) findViewById(R.id.textView_tobar_left);
        textView_tobar_left.setVisibility(View.VISIBLE);
        tv_back = (TextView) findViewById(R.id.textview_message);
        tv_back.setVisibility(View.VISIBLE);
        tv_back.setText("退出");
        order_tobar_back = (ImageView) findViewById(R.id.imageview_topbar_left_backImage);
        order_tobar_back.setVisibility(View.INVISIBLE);
        order_tobar_back.setImageResource(R.mipmap.return_key);
        order_tobar_enter = (TextView) findViewById(R.id.toolbar_topname);
        order_tobar_right = (ImageView) findViewById(R.id.imageview_message);
        order_tobar_right.setVisibility(View.GONE);
        order_layout_topbar_left = (LinearLayout) findViewById(R.id.layout_topbar_left);
        order_layout_topbar_left.setVisibility(View.VISIBLE);

        shop_search_edit = (EditText) findViewById(R.id.shop_search_edit);
        shop_search_tv = (TextView) findViewById(R.id.shop_search_tv);

        listView = (ListView) findViewById(R.id.hlist);
        btn_fh = (Button) findViewById(R.id.fh);
        btn_fh.setOnClickListener(this);
        swp = (SwipeRefreshLayout) findViewById(R.id.swp);
        swp.setOnRefreshListener(this);
        shop_search_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String trim = shop_search_edit.getText().toString().trim();
                if (trim == null || trim.length() == 0) {
                    ToastUtil.toast("不能为空");
                }
                if (trim != null && trim.length() == 11) {
                    loadData(trim);
                } else {
                    ToastUtil.toast("请输入正确的手机号");
                }
            }


        });
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AccountManager.logout(OperateActivity.this);
                SharedPreferencesHelper.setBoolean(getApplicationContext(),
                        SharedPreferencesHelper.Field.IS_COME_BACK, false);
                ActivityCollector.finishAll();
                Intent intent = new Intent(OperateActivity.this, LoginActivity.class);
                intent.putExtra(LoginActivity.TAG_IS_CAN_NOT_BACK, true);
                startActivity(intent);
                IMFactory.logout();
                MobclickAgent.onProfileSignOff();
            }
        });

        shop_search_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String trim = s.toString().trim();
                Log.e("TAG", "onTextChanged: " + trim);
                if (trim.equals("") || trim.length() == 0) {
                    Log.e("TAG", "onTextChanged: " + trim);
                    if (flag) {
                        Log.e("TAG", "onTextChanged: " + trim);
                        network();
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void loadData(String phone) {
        Map<String, String> headerParams = RequestParam.getHeaderParams();
        Map<String, String> body = new HashMap<>();
        body.put("phone", phone);
        Okhttputils.Instanse(this).postFromBody(headerParams, HttpConfig.BASE_HOST_URL + NewHttpCofig.operateSearchOrder, body, new Okhttputils.OkutListener() {
            @Override
            public void error(Call call, IOException e) {

            }

            @Override
            public void error(Call call, int code) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.toast("该手机号没有订单");
                    }
                });

            }

            @Override
            public void suseff(Call call, Response response, Object o) {
                OperateEntity operateEntity = (OperateEntity) o;
                final List<OperateEntity.DataBeanX.DateBean> date = operateEntity.getData().getDate();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        flag = true;
                        myadapter = new Myadapter(getApplicationContext(), date, false);
                        listView.setAdapter(myadapter);
                    }
                });
            }
        }, OperateEntity.class);
    }

    @Override
    public void onClick(View v) {
        if (!flag) {
            if (myadapter != null && myadapter.getdata().size() > 0) {
//            List<OperateEntity.DataBeanX.DateBean> getdata = myadapter.getdata();
                List<OperateEntity.DataBeanX.DateBean> getdata = myadapter.getdata();
                String orderids = "";
                for (int i = 0; i < getdata.size(); i++) {
                    OperateEntity.DataBeanX.DateBean dataBean = getdata.get(i);

                    if (dataBean.ischecked()) {
                        String orderid = dataBean.getOrderid();
                        if (orderids.length() > 0) {
                            orderids += "_" + orderid;
                        } else {
                            orderids += orderid;
                        }

                    }
                }
//            orderids
                ShopHttpConfig.push(OperateActivity.this, orderids, new Okhttputils.OkutListener() {
                    @Override
                    public void error(Call call, IOException e) {

                    }

                    @Override
                    public void error(Call call, int code) {

                    }

                    @Override
                    public void suseff(Call call, Response response, Object o) {
                        BaseEntity baseEntity = (BaseEntity) o;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.toast("提交成功");
                                network();
                            }
                        });
                    }
                }, BaseEntity.class);

            } else {
                ToastUtil.toast("数据获取失败或没有可选择订单");
            }
        }
    }

    @Override
    public void onRefresh() {
        network();
        swp.setRefreshing(false);
    }

    class Myadapter extends MyBaseAdapter<OperateEntity.DataBeanX.DateBean> implements CompoundButton.OnCheckedChangeListener, View.OnClickListener {

        private final LayoutInflater from;

        public Myadapter(Context ctx, List<OperateEntity.DataBeanX.DateBean> list, boolean flag) {
            super(ctx, list, flag);
            from = LayoutInflater.from(ctx);
        }

        @Override
        public View getView(int pos, View view, ViewGroup group) {
            ViewHolder viewHolder;
            if (view == null) {
                viewHolder = new ViewHolder();
                view = from.inflate(R.layout.operaitemlayout, null);
                viewHolder.tv_orid = (TextView) view.findViewById(R.id.ac_op_orderid);
                viewHolder.ac_op_if = (CheckBox) view.findViewById(R.id.ac_op_if);
                viewHolder.linearLayout = (LinearLayout) view.findViewById(R.id.lintt);
                viewHolder.ac_op_details = (TextView) view.findViewById(R.id.ac_op_details);
                viewHolder.ac_op_phone = (TextView) view.findViewById(R.id.ac_op_phone);
                viewHolder.ac_op_name = (TextView) view.findViewById(R.id.ac_op_name);
                viewHolder.ac_op_login_phone = (TextView) view.findViewById(R.id.ac_op_login_phone);
                viewHolder.ac_op_paytime = (TextView) view.findViewById(R.id.ac_op_paytime);
                viewHolder.ac_op_listView = (ListView) view.findViewById(R.id.ac_op_listView);
                viewHolder.ac_op_beizhu = (TextView) view.findViewById(R.id.ac_op_beizhu);
                viewHolder.ac_op_details_address = (TextView) view.findViewById(R.id.ac_op_details_address);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }
            viewHolder.linearLayout.setTag(pos);
            viewHolder.linearLayout.setOnClickListener(this);
            viewHolder.tv_orid.setText("订单编号:" + list.get(pos).getOrderid());
            viewHolder.ac_op_details.setText("送货地址:" + list.get(pos).getDetails());
            viewHolder.ac_op_phone.setText("收货人手机号:" + list.get(pos).getRePhone());
            viewHolder.ac_op_login_phone.setText("登录手机号" + list.get(pos).getBookPhone());
            viewHolder.ac_op_name.setText("收货人姓名:" + list.get(pos).getReName());
            viewHolder.ac_op_paytime.setText("支付时间:" + list.get(pos).getPayTime());
            if (list.get(pos).getOther() != null) {
                viewHolder.ac_op_beizhu.setText("备注:" + list.get(pos).getOther());
            }
            viewHolder.ac_op_details_address.setText("详细地址:" + list.get(pos).getReAddress());
            viewHolder.ac_op_listView.setAdapter(new ShopAdapter(list.get(pos).getData()));
            viewHolder.ac_op_if.setTag(pos);
            viewHolder.ac_op_if.setOnCheckedChangeListener(this);
            viewHolder.ac_op_if.setChecked(list.get(pos).ischecked());
            return super.getView(pos, view, group);
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            int pos = (int) buttonView.getTag();
            list.get(pos).setIschecked(isChecked);
        }

        @Override
        public void onClick(View v) {
//            int tag = (int) v.getTag();
//            OperateEntity.DataBeanX.DateBean dataBean = list.get(tag);
//            String orderid = dataBean.getOrderid();
//            Intent intent = new Intent();
//            intent.putExtra("orderid", orderid);
//            intent.setClass(OperateActivity.this, OperateDelatis.class);
//            startActivity(intent);
        }

        class ViewHolder {
            TextView tv_orid;
            CheckBox ac_op_if;
            LinearLayout linearLayout;
            ListView ac_op_listView;
            TextView ac_op_details, ac_op_phone, ac_op_name, ac_op_login_phone, ac_op_paytime, ac_op_beizhu, ac_op_details_address;
        }
    }

    class ShopAdapter extends BaseAdapter {
        List<OperateEntity.DataBeanX.DateBean.DataBean> dataBeen;

        public ShopAdapter(List<OperateEntity.DataBeanX.DateBean.DataBean> data) {
            this.dataBeen = data;
        }

        @Override
        public int getCount() {
            return dataBeen != null ? dataBeen.size() : 0;
        }

        @Override
        public Object getItem(int position) {
            return dataBeen.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            shopViewHolder holder1 = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.operateshoplistitem, null, false);
                holder1 = new shopViewHolder();
                holder1.ac_op_buyNum = (TextView) convertView.findViewById(R.id.ac_op_buyNum);
                holder1.ac_op_proName = (TextView) convertView.findViewById(R.id.ac_op_proName);
                convertView.setTag(holder1);
            } else {
                holder1 = (shopViewHolder) convertView.getTag();
            }
            holder1.ac_op_proName.setText("商品名称:" + dataBeen.get(position).getProName());
            holder1.ac_op_buyNum.setText("商品数量:x" + dataBeen.get(position).getBuyNum());
            return convertView;
        }

        class shopViewHolder {
            TextView ac_op_proName, ac_op_buyNum;
        }
    }
}
